#include <stdio.h>
#include "global.h"
#include "MsgUtil.h"
#include <pthread.h>
#include <glib.h>

//存储 ip 和 sn 变量
gchar *gatewayIp=NULL;
gchar *sn=NULL;

/*
    1.boa还没有配置，心跳进程先去获取，获取不到  -正常
    2.boa已经配置过了，读取数据一直存储在内存中了  【万一配置错误】，IP地址后面发生更改的情况
*/
gchar *getGatwayIP(){
    if(getGatwayIP!=NULL)
    {
        return gatewayIp;
    }
    //正常的去文件里面读取
    //2.1 获取要保存文件路径
    GKeyFile *configKeyFile = g_key_file_new();
    //加载文件读取配置文件存储位置
    if(!g_key_file_load_from_file(configKeyFile,"./config.ini",G_KEY_FILE_NONE,NULL)){
      g_warning("load config.ini error!");
      return gatewayIp;
    }
    gchar *deviceInfoPath = g_key_file_get_string(configKeyFile,"config","deviceInfoPath",NULL);
    //2.2 把信息写到那个文件中
    GKeyFile *deviceInfoFile = g_key_file_new();
    if(!g_file_test(deviceInfoPath,G_FILE_TEST_EXISTS))
    {
        return gatewayIp;
    }
    if(!g_key_file_load_from_file(deviceInfoFile,deviceInfoPath,G_KEY_FILE_NONE,NULL)){
    g_warning("load config.ini error!");
    return gatewayIp;
    }
    gatewayIp=g_key_file_get_string(deviceInfoFile,"config","gatewayIp",NULL);

    g_key_file_free(deviceInfoFile);
     g_key_file_free(configKeyFile);

     //return getGatwayIP;
}

gchar *getSn()
{
    //如果sn已经有值 直接返回
    if(sn!=NULL)
    {
        return sn;
    }
    //读取系统文件 返回数据
    //打开文件
    //FILE* file =  fopen("/sys/class/dmi/id/product_serial","r");
    //给sn分配空间
    //sn = (gchar *)calloc(1,128);
    //读取一行数据到sn
    //fgets(sn,128,file);
    sn = "jjjjjjjjj";
    g_print("sn=%s\n",sn);
    return sn;
}

void* recvConfigMsg(void* param){
    while (1)
    {
       int mqId = getMsgQueue(PATHNAME_BOA_MAIN,PROCESS_ID_BOA_MAIN);
        if (mqId==-1)
        {
            perror("get msg queue error!");
            pthread_exit(NULL);
        }
        Message msg = {};
        printf("start recv msg!\n");
        int recvSize = recvMsg(mqId,&msg,MSG_SIZE);
        printf("%d\n",recvSize);
        if (recvSize==-1)
        {
            perror("send data error!");
            pthread_exit(NULL);
        }

        //发起请求到服务端
        printf("type =%ld, msg=%s\n",msg.type,msg.text);
    }
}
int main(int argc, char const *argv[])
{
    printf("heart process started!\n");
    //1 接收配置的消息，做配置
    //为了不阻塞后面逻辑，要放到线程中去做处理
    pthread_t tid;
    pthread_create(&tid,NULL,recvConfigMsg,NULL);
    //2 还要做心跳逻辑
    while (1)
    {
        sleep(5);
        gchar* iptemp=getGatwayIP();
        printf("ip value :%s\n",iptemp);
        printf("send heart request!\n");
        if(iptemp==NULL)
        {
            continue;
        } 
        sleep(5);
    }

    return 0;
}
